package com.zlf.sb.demo.producer;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlf.sb.demo.entity.UserEntity;
import com.zlf.sb.demo.entity.UserJsonDataEntity;
import com.zlf.sb.demo.mapper.UserMapper;
import com.zlf.sb.demo.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class QueryDoBizProducer implements Runnable {

    private LinkedBlockingQueue<List<UserJsonDataEntity>> linkedBlockingQueue;

    private AtomicInteger count;

    private UserMapper mapper;

    private long current;

    private int pageSize;

    private CountDownLatch countDownLatch;

    public QueryDoBizProducer(LinkedBlockingQueue<List<UserJsonDataEntity>> linkedBlockingQueue, long current, AtomicInteger count, CountDownLatch countDownLatch, int pageSize) throws Exception {
        this.linkedBlockingQueue = linkedBlockingQueue;
        this.mapper = SpringUtils.getBean(UserMapper.class);
        this.current = current;
        this.count = count;
        this.countDownLatch = countDownLatch;
        this.pageSize = pageSize;
    }

    @Override
    public void run() {
        try {
            Page<UserEntity> page2 = new Page<>(current, pageSize);
            QueryWrapper<UserEntity> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().orderByDesc(UserEntity::getCreateTime);
            Page<UserEntity> pageData = mapper.selectPage(page2, queryWrapper2);
            if (Objects.nonNull(pageData)) {
                List<UserEntity> records = pageData.getRecords();
                List<UserJsonDataEntity> list = new ArrayList<>();
                for (UserEntity rs : records) {
                    UserJsonDataEntity jd = JSONObject.parseObject(rs.getJsonData(), new TypeReference<UserJsonDataEntity>() {
                    });
                    list.add(jd);
                }
                linkedBlockingQueue.put(list);
                count.getAndAdd(list.size());
                log.info("生产者查询数据放入队列完成---->ThreadName:{}", Thread.currentThread().getName());
            }
            countDownLatch.countDown();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("加入队列异常:{}", e.getMessage());
        }
    }

}
